<template>
  <div ref="radarChart" style="width: 100%; height: 290px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';

export default {
  name: 'RadarChart',
  data() {
    return {
      radarChart: null,
      chartData: [],
    };
  },
  methods: {
    async fetchData() {
      try {
        const response = await axios.get('/api/queryAllSoldBodyTimes');
        if (response.data.code === '200') {
          this.chartData = response.data.data;
          this.initChart();
        } else {
          console.error('Error fetching data:', response.data.msg);
        }
      } catch (error) {
        console.error('API error:', error);
      }
    },
    initChart() {
      if (!this.chartData.length) return;

      const groupedData = {};
      this.chartData.forEach((item) => {
        if (!groupedData[item.year]) {
          groupedData[item.year] = [];
        }
        groupedData[item.year].push({
          name: item.bodyType,
          value: item.totalUnitsSold,
        });
      });

      const years = Object.keys(groupedData);
      const bodyTypes = [
        ...new Set(this.chartData.map((item) => item.bodyType)),
      ];

      const radarIndicators = bodyTypes.map((bodyType) => {
      const bodyTypeData = this.chartData.filter((item) => item.bodyType === bodyType);
      const maxValue = Math.max(...bodyTypeData.map((item) => item.totalUnitsSold));
      const overallMax = Math.max(...this.chartData.map((item) => item.totalUnitsSold));

      let max = maxValue;
      if (maxValue !== overallMax) {
        if (maxValue === Math.max(...this.chartData.map((item) => item.totalUnitsSold), 2)) {
          max = maxValue * 1.7;
        } else if (maxValue !== Math.max(...this.chartData.map((item) => item.totalUnitsSold), 1)) {
          max = maxValue * 2;
        }
      }

      return {
        text: bodyType,
        max: max,
      };
    });


      const series = years.map((year) => ({
        type: 'radar',
        name: year,
        data: [
          {
            value: bodyTypes.map(
              (type) =>
                groupedData[year].find((item) => item.name === type)?.value || 0
            ),
            name: year,
          },
        ],
      }));

      const option = {
        title: {
          text: '不同车型车辆销售数据',
          top:8,
          left:'center',
          textStyle: {
            color: '#FFFFFF', // 图例文字颜色设置为白色
            fontFamily:'YouYuan'
          },
        },
        tooltip: {},
        legend: {
          data: years,
          bottom: 10,
          textStyle: {
            color: '#FFFFFF', // 图例文字颜色设置为白色
          },
        },
        
        radar: {
          radius: '55%', 
          indicator: radarIndicators,
          shape: 'polygon',
        },
        series,
      };

      this.radarChart.setOption(option);
    },
  },
  mounted() {
    this.radarChart = echarts.init(this.$refs.radarChart);
    this.fetchData();

    window.addEventListener('resize', () => {
      if (this.radarChart) {
        this.radarChart.resize();
      }
    });
  },
  beforeDestroy() {
    if (this.radarChart) {
      this.radarChart.dispose();
    }
  },
};
</script>

<style>

</style>
